<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="科室" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入科室"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="接诊类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择接诊类型" clearable style="width: 100px;">
          <el-option
            v-for="dict in doctor_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="医生id" prop="doctorId">
        <el-input
          v-model="queryParams.doctorId"
          placeholder="请输入医生id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="患者" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者id"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="就诊状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择就诊状态" clearable style="width: 100px;">
          <el-option
            v-for="dict in fy_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['chy:guahao:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['chy:guahao:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['chy:guahao:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['chy:guahao:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="guahaoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="挂号单号" align="center" prop="id" />
      <el-table-column label="科室" align="center" prop="deptId" >
        <template #default="scope">
          <span v-for="d in deptList" :key="d">
            <!-- {{ d.deptId }}|
            {{ scope.row.deptId }} -->
            <!-- {{ d.deptName }} -->
            <span v-if="scope.row.deptId == d.deptId">
              {{ d.deptName }}
            </span>
            </span>
          </template>
        </el-table-column>
      <el-table-column label="接诊类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="doctor_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="接诊医生" align="center" prop="doctorId" >
        <template #default="scope">
          <span v-for="u in userList" :key="u">
            <!-- {{ u.userId }}|
            {{ scope.row.doctorId }} -->
            <!-- {{ u.userName }} -->
            <span v-if="scope.row.doctorId == u.userId">
              {{ u.nickName }}
            </span>
            </span>
          </template>
        </el-table-column>
      <el-table-column label="挂号费" align="center" prop="money" >
        <template #default="scope">
          <span v-for="r in registationcostList" :key="r">
            <!-- {{ u.id }}|
            {{ scope.row.id }} -->
            <!-- {{ u.registationCost }} -->
            <span v-if="scope.row.money == r.id">
              {{ r.registrationCost+"元" }}
            </span>
            </span>
          </template>
        </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          
        </template>
      </el-table-column>
      <el-table-column label="患者" align="center" prop="patientId" >
        <template #default="scope">
          <span v-for="p in patientList" :key="p">
            <!-- {{ p.id }}|
            {{ scope.row.patientId }} -->
            <!-- {{ p.name }} -->
            <span v-if="scope.row.patientId == p.id">
              {{ p.name }}
            </span>
            </span>
          </template>
        </el-table-column>
      <el-table-column label="就诊状态" align="center" prop="state">
        <template #default="scope">
          <dict-tag :options="fy_status" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['chy:guahao:edit']">收费</el-button> -->
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['chy:guahao:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['chy:guahao:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改挂号记录对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="guahaoRef" :model="form" :rules="rules" label-width="100px">
        <div class="registration-info">
          <el-row>
            <el-col :span="12">
              <el-form-item label="挂号单号" prop="id">
                <el-input v-model="form.id" disabled placeholder="系统自动生成" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="科室" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in deptList"
                    :key="dict.deptId"
                    :label="dict.deptName"
                    :value="dict.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="接诊类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in doctor_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="接诊医生" prop="doctorId">
                <el-select v-model="form.doctorId" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in userList"
                    :key="dict.userId"
                    :label="dict.nickName"
                    :value="dict.userId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="挂号费" prop="money">
                <el-select v-model="form.money" placeholder="请选择" style="width: 100%">
                  <el-option
                    v-for="dict in registationcostList"
                    :key="dict.id"
                    :label="dict.registrationCost+'元'"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="挂号日期" prop="createTime">
                <!-- <el-date-picker
                  v-model="form.createTime"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                /> -->
                <el-date-picker
                  v-model="form.createTime"
                  type="date"
                   placeholder="选择日期"
                   value-format="YYYY-MM-DD"
                   style="width: 100%"
                  :size="size"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="挂号员" prop="createPeople">
                <el-input v-model="form.createPeople" placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row> -->
        </div>

        <div class="patient-info">
          <div class="section-title">患者信息</div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="患者姓名" prop="from_patient.name">
                <el-input
                  v-model="form.from_patient.name"
                  placeholder="请输入患者姓名/手机号码/证件号码/卡号"
                  @blur="searchPatient($event.target.value)"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="患者卡号" prop="from_patient.id">
                <el-input
                  v-model="form.from_patient.id"
                  placeholder="请输入就诊卡号"
                  @blur="searchPatient($event.target.value)"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="患者年龄" prop="from_patient.age">
                <el-input-number v-model="form.from_patient.age" :min="0" :max="150" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="from_patient.birthday">
                <el-date-picker
                  v-model="form.from_patient.birthday"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <!-- <el-form-item label="性别" prop="from_patient.sex">
                <el-select v-model="form.from_patient.sex" placeholder="请选择" style="width: 100%">
                  <el-option label="男" value="男" />
                  <el-option label="女" value="女" />
                </el-select>
              </el-form-item> -->

              <el-form-item label="性别" prop="sex">
          <el-select v-model="form.from_patient.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="from_patient.phone">
                <el-input
                  v-model="form.from_patient.phone"
                  placeholder="请输入手机号码"
                  @blur="searchPatient($event.target.value)"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="证件号码" prop="from_patient.idNumber">
                <el-input
                  v-model="form.from_patient.idNumber"
                  placeholder="请输入证件号码"
                  @blur="searchPatient($event.target.value)"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="地址" prop="from_patient.address">
                <!-- <el-cascader
                  v-model="from_patient.address"
                  placeholder="请选择地址"
                  style="width: 200px"
                /> -->
                <el-input
                  v-model="form.from_patient.address"
                  placeholder="请输入详细地址"
                  style="width: calc(100% - 210px); margin-left: 10px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="from_patient.remark">
                <el-input
                  v-model="form.from_patient.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注信息"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Guahao">
import { listGuahao, getGuahao, delGuahao, addGuahao, updateGuahao } from "@/api/chy/guahao";
import { listDept } from "@/api/system/dept";
import { listUser } from "@/api/system/user";
import { listPatient, addPatient, updatePatient } from "@/api/chy/patient";
import { listRegistationcost } from "@/api/chy/registationcost";
const { proxy } = getCurrentInstance();
const { doctor_type, fy_status } = proxy.useDict('doctor_type', 'fy_status');
const { sys_user_sex } = proxy.useDict('sys_user_sex');
const guahaoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptList = ref([]);
const userList = ref([]);
const patientList = ref([]);
const registationcostList = ref([]);

const data = reactive({
  form: {
    id: null,
    deptId: null,
    type: null,
    doctorId: null,
    money: null,
    createTime: null,
    createPeople: null,
    patientId: null,
    state: null,
    from_patient: {
      id: null,
      name: null,
      password: null,
      sex: null,
      age: null,
      birthday: null,
      phone: null,
      idNumber: null,
      department: null,
      vipType: null,
      daedLine: null,
      nation: null,
      marriagestatus: null,
      address: null,
      education: null,
      career: null,
      workUnit: null,
      remark: null,
      del: null
    }
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    type: null,
    doctorId: null,
    createTime: null,
    patientId: null,
    state: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询挂号记录列表 */
function getList() {
  loading.value = true;
  listGuahao(queryParams.value).then(response => {
    guahaoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    type: null,
    doctorId: null,
    money: null,
    createTime: null,
    createPeople: null,
    patientId: null,
    state: null,
    from_patient: {
      id: null,
      name: null,
      password: null,
      sex: null,
      age: null,
      birthday: null,
      phone: null,
      idNumber: null,
      department: null,
      vipType: null,
      daedLine: null,
      nation: null,
      marriagestatus: null,
      address: null,
      education: null,
      career: null,
      workUnit: null,
      remark: null,
      del: null
    }
  };
  proxy.resetForm("guahaoRef");
}
//查询部门列表
async function getDeptList() {
  try {
    loading.value = true;
    const response = await listDept(); // 等待异步操作完成
    deptList.value = response.data;
    
  } catch (error) {
    console.error('Error fetching department list:', error);
  } finally {
    loading.value = false;
  }
  // console.log(deptList.value); // 数据加载完成后打印
}
//查询用户列表
async function getUserList() {
  try {
    loading.value = true;

    // 调用异步方法并等待结果
    const res = await listUser();

    // 更新数据
    userList.value = res.rows;

    // 打印更新后的 userList 数据
    // console.log(userList.value);
  } catch (error) {
    console.error('Error fetching user list:', error);
  } finally {
    // 确保加载状态被重置
    loading.value = false;
  }
}
//查询患者列表
async function getPatientList() {
  try {
    loading.value = true;

    // 调用异步方法并等待结果
    const response = await listPatient();

    // 更新数据
    patientList.value = response.rows;
  } catch (error) {
    console.error('Error fetching patient list:', error);
  } finally {
    // 确保加载状态被重置
    loading.value = false;
  }
  // console.log(patientList.value);
}
//查询挂号费用列表
async function getRegistationcostList() {
  try {
    loading.value = true;

    // 调用异步方法并等待结果
    const response = await listRegistationcost();
    console.log('Registation cost list response:', response);
    // 更新数据
    registationcostList.value = response.rows; 
  }  
  catch (error) {
    console.error('Error fetching registation cost list:', error); 
  }finally {
    // 确保加载状态被重置
    loading.value = false; 
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  // 重置表单时保持一些默认值
  form.value = {
    ...form.value,
    createTime: new Date().toISOString().split('T')[0], // 默认当前日期
    createPeople: userList.value.userId, // 默认挂号员
    state: 1, // 默认就诊状态为1
    from_patient: {
      id: null,
      name: null,
      password: null,
      sex: null,
      age: null,
      birthday: null,
      phone: null,
      idNumber: null,
      department: null,
      vipType: null,
      daedLine: null,
      nation: null,
      marriagestatus: null,
      address: null,
      education: null,
      career: null,
      workUnit: null,
      remark: null,
      del: null
    }
  };
  open.value = true;
  title.value = "新增挂号";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  try {
    // 获取挂号信息
    const guahaoResponse = await getGuahao(_id);
    form.value = {
      ...guahaoResponse.data,
      from_patient: {
        id: null,
        name: null,
        password: null,
        sex: null,
        age: null,
        birthday: null,
        phone: null,
        idNumber: null,
        department: null,
        vipType: null,
        daedLine: null,
        nation: null,
        marriagestatus: null,
        address: null,
        education: null,
        career: null,
        workUnit: null,
        remark: null,
        del: null
      }
    };
    
    // 获取患者信息
    if (form.value.patientId) {
      // 直接使用 patientId 查询患者信息
      const patientResponse = await listPatient({ id: form.value.patientId });
      if (patientResponse.rows && patientResponse.rows.length > 0) {
        const patient = patientResponse.rows[0];
        // 更新患者信息
        form.value.from_patient = {
          id: patient.id,
          name: patient.name,
          sex: patient.sex,
          age: patient.age,
          birthday: patient.birthday,
          phone: patient.phone,
          idNumber: patient.idNumber,
          department: patient.department,
          vipType: patient.vipType,
          daedLine: patient.daedLine,
          nation: patient.nation,
          marriagestatus: patient.marriagestatus,
          address: patient.address,
          education: patient.education,
          career: patient.career,
          workUnit: patient.workUnit,
          remark: patient.remark,
          del: patient.del
        };
      }
    }
    
    open.value = true;
    title.value = "修改挂号记录";
  } catch (error) {
    console.error('Error fetching data:', error);
    proxy.$modal.msgError("获取数据失败：" + error.message);
  }
}

// 修改搜索患者方法，避免在修改时覆盖已有患者信息
async function searchPatient(query) {
  if (!query) return;
  
  // 如果是修改操作，不执行搜索
  if (form.value.id) return;
  
  try {
    // 根据输入的查询条件搜索患者
    const response = await listPatient({
      name: query,
      phone: query,
      idCard: query,
      cardNo: query
    });
    
    if (response.rows && response.rows.length > 0) {
      const patient = response.rows[0];
      // 填充患者信息到表单
      form.value.from_patient = {
        id: patient.id,
        name: patient.name,
        sex: patient.sex,
        age: patient.age,
        birthday: patient.birthday,
        phone: patient.phone,
        idNumber: patient.idNumber,
        department: patient.department,
        vipType: patient.vipType,
        daedLine: patient.daedLine,
        nation: patient.nation,
        marriagestatus: patient.marriagestatus,
        address: patient.address,
        education: patient.education,
        career: patient.career,
        workUnit: patient.workUnit,
        remark: patient.remark,
        del: patient.del
      };
      // 设置patientId用于关联
      form.value.patientId = patient.id;
    }
  } catch (error) {
    console.error('Error searching patient:', error);
  }
}

/** 提交按钮 */
async function submitForm() {
  proxy.$refs["guahaoRef"].validate(async (valid) => {
    if (valid) {
      try {
        // 确保 from_patient 存在
        if (!form.value.from_patient) {
          form.value.from_patient = {
            id: null,
            name: null,
            password: null,
            sex: null,
            age: null,
            birthday: null,
            phone: null,
            idNumber: null,
            department: null,
            vipType: null,
            daedLine: null,
            nation: null,
            marriagestatus: null,
            address: null,
            education: null,
            career: null,
            workUnit: null,
            remark: null,
            del: null
          };
        }

        // 准备患者数据
        const patientData = {
          id: form.value.from_patient.id,
          name: form.value.from_patient.name,
          sex: form.value.from_patient.sex,
          age: form.value.from_patient.age,
          birthday: form.value.from_patient.birthday,
          phone: form.value.from_patient.phone,
          idNumber: form.value.from_patient.idNumber,
          department: form.value.from_patient.department,
          vipType: form.value.from_patient.vipType,
          daedLine: form.value.from_patient.daedLine,
          nation: form.value.from_patient.nation,
          marriagestatus: form.value.from_patient.marriagestatus,
          address: form.value.from_patient.address,
          education: form.value.from_patient.education,
          career: form.value.from_patient.career,
          workUnit: form.value.from_patient.workUnit,
          remark: form.value.from_patient.remark,
          del: form.value.from_patient.del
        };

        let patientId;
        // 如果是修改操作且已有患者ID
        if (form.value.from_patient.id) {
          await updatePatient(patientData);
          patientId = form.value.from_patient.id;
        } else {
          // 新增患者
          const response = await addPatient(patientData);
          patientId = response.data;
        }

        // 准备挂号数据，添加时间部分到日期
        const formattedDate = form.value.createTime ? form.value.createTime + ' 00:00:00' : null;
        
        // 准备挂号数据
        const registrationData = {
          id: form.value.id,
          deptId: form.value.deptId,
          type: form.value.type,
          doctorId: form.value.doctorId,
          money: form.value.money,
          createTime: formattedDate,
          createPeople: form.value.createPeople,
          patientId: patientId,
          state: form.value.state || 1  // 如果没有设置状态，默认为1
        };

        if (form.value.id != null) {
          await updateGuahao(registrationData);
          proxy.$modal.msgSuccess("修改成功");
        } else {
          await addGuahao(registrationData);
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error('Error submitting form:', error);
        proxy.$modal.msgError("操作失败：" + error.message);
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除挂号记录编号为"' + _ids + '"的数据项？').then(function() {
    return delGuahao(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('chy/guahao/export', {
    ...queryParams.value
  }, `guahao_${new Date().getTime()}.xlsx`)
}

getList();
getDeptList();
getUserList();
getPatientList();
getRegistationcostList();
</script>

<style scoped>
.section-title {
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin: 20px 0 15px 0;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.el-row {
  margin-bottom: 15px;
}

.age-unit {
  margin-left: 5px;
}

.el-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}
</style>
